package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuReductionTO;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignSerivce;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuInfoRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionVo;
import com.atguigu.gulimall.seckill.vo.SeckillSkuRelationVo;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author 马迎迎
 * @Title: SeckillServiceImpl
 * @Package com.atguigu.gulimall.seckill.service.impl
 * @Description: TODO(添加描述)
 * @date 2021年06月02日 13:49
 */
@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private ProductFeignSerivce productFeignSerivce;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUS_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE_PREFIX = "seckill:stock:";//加商品随机码

    @Override
    public void updateSeckillSkuLasted3Days() {
        //1.去扫描最近三天需要参与秒杀的活动
        R r = couponFeignService.getLatest3DaysSession();
        if (r.getCode() == 0) {
            //上架商品
            List<SeckillSessionVo> sessions = r.getData(new TypeReference<List<SeckillSessionVo>>() {
            });
            //缓存到redis中
            //1.缓存活动信息
            saveSessionInfos(sessions);
            //2.缓存活动关联的商品信息
            saveSkuInfos(sessions);
        }

    }
    public List<SeckillSkuInfoRedisTo> blockHandler(BlockException e) {
        log.error("getCurrentTimeSeckillSkusResource被限流了");
        return null;
    }
    //返回当前时间可以参与秒杀的商品信息
    @SentinelResource(value = "getCurrentTimeSeckillSkusResource",blockHandler = "blockHandler",fallback = "")
    @Override
    public List<SeckillSkuInfoRedisTo> getCurrentTimeSeckillSkus() {
        //1.确定当前时间属于哪个秒杀场次
        long currentTime = new Date().getTime();
        try(Entry entry = SphU.entry("SeckillSkus")) {
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                String s = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s1 = s.split("_");
                Long startTime = Long.parseLong(s1[0]);
                Long endTime = Long.parseLong(s1[1]);
                if (currentTime >= startTime && currentTime <= endTime) {
                    //2.获取这个秒杀场次的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                    BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
                    List<String> list = hashOps.multiGet(range);
                    if (list != null) {
                        List<SeckillSkuInfoRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuInfoRedisTo seckillSkuInfoRedisTo = JSON.parseObject(item, SeckillSkuInfoRedisTo.class);
//                        seckillSkuInfoRedisTo.setRandomCode(null);  当前秒杀开始需要随机码
                            return seckillSkuInfoRedisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }

        } catch (BlockException e){
            log.error("资源被限流,{}",e.getMessage());
        }

        return null;
    }

    @Override
    public SeckillSkuInfoRedisTo getSkuSeckillInfo(Long skuId) {
        //1.找到所有需要参与秒杀的key信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String reg = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(reg, key)) {
                    SeckillSkuInfoRedisTo res = JSON.parseObject(hashOps.get(key), SeckillSkuInfoRedisTo.class);
                    long currentTime = new Date().getTime();
                    if (currentTime >= res.getStartTime() && currentTime <= res.getEndTime()) {

                    } else {
                        res.setRandomCode(null);
                    }
                    //随机码
                    return res;
                }
            }
        }
        return null;
    }

    //TODO 秒杀业务细化信息：上架秒杀商品的时候，每个数据都有过期时间
    //TODO 秒杀业务细化信息：秒杀后续的流程，简化了收获地址等信息
    @Override
    public String seckill(String seckillId, Integer count, String seckillToken) {
        long l1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
        String value = hashOps.get(seckillId);//3_1
        if (StringUtils.isEmpty(value)) {
            return null;
        } else {
            SeckillSkuInfoRedisTo redis = JSON.parseObject(value, SeckillSkuInfoRedisTo.class);
            //校验合法性
            //1.校验时间的合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long currentTime = new Date().getTime();
            long ttl = endTime - currentTime;

            if (currentTime >= startTime && currentTime <= endTime) {
                //2.校验随机码和商品id
                String redisId = redis.getPromotionSessionId().toString() + "_" + redis.getSkuId().toString();
                if (redis.getRandomCode().equals(seckillToken) && redisId.equals(seckillId)) {
                    //3.验证购买数量是否合理
                    if (redis.getSeckillLimit().intValue() >= count) {
                        //4.验证这个人是否购买过。幂等性处理：只要秒杀成功，就去redis里占位(使用key占位)。userId_sessionId_skuId
                        //setnx
                        String u_s_s = memberRespVo.getId() + "_" + seckillId;
                        //自动过期
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(u_s_s, count.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功，说明该用户在秒杀时间内从来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE_PREFIX + seckillToken);

                            boolean b = semaphore.tryAcquire(count);

                            if (b) {
                                //秒杀成功
                                //快速下单 发送MQ消息
//                                String orderSn = IdWorker.getTimeId();
                                String orderSn = UUID.randomUUID().toString();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(orderSn);
                                seckillOrderTo.setMemberId(memberRespVo.getId());
                                seckillOrderTo.setNum(count);
                                seckillOrderTo.setSkuId(redis.getSkuId());
                                seckillOrderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                seckillOrderTo.setSeckillPrice(redis.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order",seckillOrderTo);
                                long l2 = System.currentTimeMillis();
                                log.info("耗时：{}毫秒",l2-l1);
                                return orderSn;
                            } else {
                                return null;
                            }


                        } else {
                            //已经买过了
                            return null;
                        }
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }

        }
    }

    public void saveSessionInfos(List<SeckillSessionVo> sessions) {
        if(sessions!=null&&sessions.size()>0){
            for (SeckillSessionVo session : sessions) {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
                Boolean hasKey = redisTemplate.hasKey(key);
                //缓存活动信息
                if (!hasKey) {
                    List<String> skuIds = session.getRelationEntities().stream().map(relation -> {
                        return relation.getPromotionSessionId().toString() + "_" + relation.getSkuId().toString();
                    }).collect(Collectors.toList());
                    redisTemplate.opsForList().leftPushAll(key, skuIds);
                }

            }
        }

    }

    public void saveSkuInfos(List<SeckillSessionVo> sessions) {
        for (SeckillSessionVo session : sessions) {
            //准备hash操作的结构
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
            for (SeckillSkuRelationVo relationEntity : session.getRelationEntities()) {
                //4.商品的随机码 seckill?key=vfksvnf 公平的秒杀
                String randomCode = UUID.randomUUID().toString().replace("-", "");
                if (!ops.hasKey(relationEntity.getPromotionSessionId().toString() + "_" + relationEntity.getSkuId().toString())) {
                    SeckillSkuInfoRedisTo seckillSkuInfoRedisTo = new SeckillSkuInfoRedisTo();
                    //sku秒杀信息
                    BeanUtils.copyProperties(relationEntity, seckillSkuInfoRedisTo);
                    //sku的基本数据
                    Long skuId = relationEntity.getSkuId();
                    R r = productFeignSerivce.getSkuInfo(skuId);
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfoVo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        seckillSkuInfoRedisTo.setSkuInfoVo(skuInfoVo);
                    }

                    //开始结束时间
                    long startTime = session.getStartTime().getTime();
                    long endTime = session.getEndTime().getTime();
                    seckillSkuInfoRedisTo.setStartTime(startTime);
                    seckillSkuInfoRedisTo.setEndTime(endTime);


                    seckillSkuInfoRedisTo.setRandomCode(randomCode);


                    String string = JSON.toJSONString(seckillSkuInfoRedisTo);
                    ops.put(relationEntity.getPromotionSessionId().toString() + "_" + skuId.toString(), string);


                    //如果当前这个场次的商品的库存信息已经上架就不需要上架
                    //5.使用库存作为分布式信号量 限量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE_PREFIX + randomCode);
                    //商品可以秒杀的件数作为信号量
                    semaphore.trySetPermits(relationEntity.getSeckillCount().intValue());

                }


            }
        }
    }
}
